'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Copy, Edit, Save, X, Search, FileText, Code, BookOpen } from 'lucide-react';

/**
 * 软件著作权申请材料生成器主页面
 * 提供软件信息输入、摘要生成、完整材料生成等功能
 */
export default function GeneratorPage() {
  // 表单数据状态：软件描述、开发语言、版本号
  const [formData, setFormData] = useState({
    description: '',
    language: '',
    version: ''
  });
  
  const [results, setResults] = useState<{
    serial_number?: string;
    application_form_summary?: string;
    code_summary?: string;
    document_summary?: string;
    application_form_full?: string;
    code_full?: string;
    document_full?: string;
  }>({});
  
  const [editingSummary, setEditingSummary] = useState<{
    application_form?: boolean;
    code?: boolean;
    document?: boolean;
  }>({});
  
  const [editedSummaries, setEditedSummaries] = useState<{
    application_form_summary?: string;
    code_summary?: string;
    document_summary?: string;
  }>({});
  
  const [loading, setLoading] = useState(false);
  const [loadingModule, setLoadingModule] = useState<{
    application_form?: boolean;
    code?: boolean;
    document?: boolean;
    all?: boolean;
  }>({});
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [activeTab, setActiveTab] = useState('summary');

  /**
   * 处理表单输入变化
   * @param field 字段名
   * @param value 字段值
   */
  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  /**
   * 生成申请材料摘要
   * 调用后端API生成登记申请表、源程序、说明文档的摘要
   */
  const generateSummary = async () => {
    // 表单验证
    if (!formData.description || !formData.language || !formData.version) {
      setError('请填写所有必填字段');
      return;
    }

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const response = await fetch('/api/generate-summary', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });

      const result = await response.json();

      if (result.success) {
        setResults(result.data);
        setEditedSummaries({
          application_form_summary: result.data.application_form_summary,
          code_summary: result.data.code_summary,
          document_summary: result.data.document_summary
        });
        setSuccess('摘要生成成功！');
      } else {
        setError(result.error || '生成失败');
      }
    } catch (error) {
      setError('网络错误：' + (error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const generateFullModule = async (module: 'application_form' | 'code' | 'document') => {
    const summaryKey = `${module}_summary` as keyof typeof editedSummaries;
    const fullKey = `${module}_full` as keyof typeof results;
    
    if (!editedSummaries[summaryKey]) {
      setError('请先编辑或生成该模块的摘要');
      return;
    }

    setLoadingModule(prev => ({ ...prev, [module]: true }));
    setError('');
    setSuccess('');

    try {
      const response = await fetch('/api/generate-full', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          [summaryKey]: editedSummaries[summaryKey],
          module,
          serial_number: results.serial_number
        })
      });

      const result = await response.json();

      if (result.success) {
        setResults(prev => ({ ...prev, [fullKey]: result.data[fullKey] }));
        setSuccess(`${getModuleTitle(module)}完整版本生成成功！`);
      } else {
        setError(result.error || '生成失败');
      }
    } catch (error) {
      setError('网络错误：' + (error as Error).message);
    } finally {
      setLoadingModule(prev => ({ ...prev, [module]: false }));
    }
  };

  const generateFullAll = async () => {
    if (!editedSummaries.application_form_summary || !editedSummaries.code_summary || !editedSummaries.document_summary) {
      setError('请确保所有摘要都已生成或编辑');
      return;
    }

    setLoadingModule(prev => ({ ...prev, all: true }));
    setError('');
    setSuccess('');

    try {
      const response = await fetch('/api/generate-full', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          application_form_summary: editedSummaries.application_form_summary,
          code_summary: editedSummaries.code_summary,
          document_summary: editedSummaries.document_summary,
          serial_number: results.serial_number
        })
      });

      const result = await response.json();

      if (result.success) {
        setResults(prev => ({ ...prev, ...result.data }));
        setSuccess('所有完整版本生成成功！');
        setActiveTab('full');
      } else {
        setError(result.error || '生成失败');
      }
    } catch (error) {
      setError('网络错误：' + (error as Error).message);
    } finally {
      setLoadingModule(prev => ({ ...prev, all: false }));
    }
  };

  const startEditing = (module: 'application_form' | 'code' | 'document') => {
    setEditingSummary(prev => ({ ...prev, [module]: true }));
  };

  const saveEditing = (module: 'application_form' | 'code' | 'document') => {
    const summaryKey = `${module}_summary` as keyof typeof editedSummaries;
    setResults(prev => ({ ...prev, [summaryKey]: editedSummaries[summaryKey] }));
    setEditingSummary(prev => ({ ...prev, [module]: false }));
    setSuccess('摘要已保存');
  };

  const cancelEditing = (module: 'application_form' | 'code' | 'document') => {
    const summaryKey = `${module}_summary` as keyof typeof results;
    setEditedSummaries(prev => ({ ...prev, [summaryKey]: results[summaryKey] }));
    setEditingSummary(prev => ({ ...prev, [module]: false }));
  };

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setSuccess('内容已复制到剪贴板');
    } catch (error) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setSuccess('内容已复制到剪贴板');
    }
  };

  const getModuleTitle = (module: string) => {
    const titles = {
      application_form: '登记申请表',
      code: '源程序',
      document: '说明文档'
    };
    return titles[module as keyof typeof titles] || module;
  };

  const getModuleIcon = (module: string) => {
    const icons = {
      application_form: FileText,
      code: Code,
      document: BookOpen
    };
    return icons[module as keyof typeof icons] || FileText;
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            软件著作权申请材料生成器
          </h1>
          <p className="text-gray-600">
            基于AI技术的智能材料生成工具
          </p>
        </div>

        {/* 错误和成功消息 */}
        {error && (
          <Alert className="mb-6 border-red-200 bg-red-50">
            <AlertDescription className="text-red-700">
              {error}
            </AlertDescription>
          </Alert>
        )}
        {success && (
          <Alert className="mb-6 border-green-200 bg-green-50">
            <AlertDescription className="text-green-700">
              {success}
            </AlertDescription>
          </Alert>
        )}

        {/* 输入表单 */}
        <Card className="mb-8">
          <CardHeader>
            <CardTitle>软件信息</CardTitle>
            <CardDescription>
              请填写您的软件基本信息，系统将为您生成专业的申请材料
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-2">
                  软件描述 *
                </label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  placeholder="请详细描述您的软件功能、特点、用途等..."
                  className="min-h-[100px]"
                />
              </div>
              
              <div>
                <label htmlFor="language" className="block text-sm font-medium text-gray-700 mb-2">
                  开发语言 *
                </label>
                <Select value={formData.language} onValueChange={(value) => handleInputChange('language', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择开发语言" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Python">Python</SelectItem>
                    <SelectItem value="Java">Java</SelectItem>
                    <SelectItem value="JavaScript">JavaScript</SelectItem>
                    <SelectItem value="TypeScript">TypeScript</SelectItem>
                    <SelectItem value="C#">C#</SelectItem>
                    <SelectItem value="C++">C++</SelectItem>
                    <SelectItem value="PHP">PHP</SelectItem>
                    <SelectItem value="Go">Go</SelectItem>
                    <SelectItem value="Rust">Rust</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              
              <div>
                <label htmlFor="version" className="block text-sm font-medium text-gray-700 mb-2">
                  版本号 *
                </label>
                <Input
                  id="version"
                  value={formData.version}
                  onChange={(e) => handleInputChange('version', e.target.value)}
                  placeholder="例如：1.0.0"
                />
              </div>
              
              {!results.application_form_summary && !results.code_summary && !results.document_summary && (
                <div className="flex justify-center">
                  <Button 
                    onClick={generateSummary} 
                    disabled={loading}
                    className="min-w-[200px]"
                  >
                    {loading ? '生成中...' : '智能生成摘要'}
                  </Button>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 一键生成完整版按钮 - 仅在摘要生成完成后显示，取代生成摘要按钮的位置 */}
        {(results.application_form_summary || results.code_summary || results.document_summary) && (
          <Card className="mb-8">
            <CardContent className="pt-6">
              <div className="flex justify-center gap-4">
                <Button 
                  onClick={generateFullAll}
                  disabled={loadingModule.all}
                  className="min-w-[200px]"
                  size="lg"
                >
                  {loadingModule.all ? '生成中...' : '一键生成完整版'}
                </Button>
                <Button 
                  onClick={generateSummary} 
                  disabled={loading}
                  variant="outline"
                  className="min-w-[200px]"
                >
                  {loading ? '生成中...' : '重新生成摘要'}
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 序列号显示 */}
        {results.serial_number && (
          <Card className="mb-8">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Search className="h-5 w-5" />
                生成记录
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">序列号</p>
                  <p className="font-mono text-lg font-semibold">{results.serial_number}</p>
                </div>
                <Button 
                  variant="outline" 
                  onClick={() => copyToClipboard(results.serial_number!)}
                  className="flex items-center gap-2"
                >
                  <Copy className="h-4 w-4" />
                  复制序列号
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 结果展示 */}
        {(results.application_form_summary || results.code_summary || results.document_summary) && (
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="summary">摘要版本</TabsTrigger>
              <TabsTrigger value="full" disabled={!results.application_form_full && !results.code_full && !results.document_full}>
                完整版本
              </TabsTrigger>
            </TabsList>
            
            <TabsContent value="summary" className="space-y-6">
              <div className="grid gap-6 md:grid-cols-1">
                {['application_form', 'code', 'document'].map((module) => {
                  const summaryKey = `${module}_summary` as keyof typeof results;
                  const Icon = getModuleIcon(module);
                  
                  return results[summaryKey] && (
                    <Card key={module}>
                      <CardHeader>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Icon className="h-5 w-5" />
                            <CardTitle>{getModuleTitle(module)}摘要</CardTitle>
                          </div>
                          <div className="flex items-center gap-2">
                            {editingSummary[module as keyof typeof editingSummary] ? (
                              <>
                                <Button 
                                  size="sm" 
                                  variant="outline"
                                  onClick={() => saveEditing(module as 'application_form' | 'code' | 'document')}
                                >
                                  <Save className="h-4 w-4" />
                                </Button>
                                <Button 
                                  size="sm" 
                                  variant="outline"
                                  onClick={() => cancelEditing(module as 'application_form' | 'code' | 'document')}
                                >
                                  <X className="h-4 w-4" />
                                </Button>
                              </>
                            ) : (
                              <>
                                <Button 
                                  size="sm" 
                                  variant="outline"
                                  onClick={() => startEditing(module as 'application_form' | 'code' | 'document')}
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button 
                                  size="sm" 
                                  variant="outline"
                                  onClick={() => copyToClipboard(results[summaryKey]!)}
                                >
                                  <Copy className="h-4 w-4" />
                                </Button>
                              </>
                            )}
                          </div>
                        </div>
                      </CardHeader>
                      <CardContent>
                        {editingSummary[module as keyof typeof editingSummary] ? (
                          <Textarea
                            value={editedSummaries[summaryKey as keyof typeof editedSummaries] || ''}
                            onChange={(e) => setEditedSummaries(prev => ({ 
                              ...prev, 
                              [summaryKey]: e.target.value 
                            }))}
                            className="min-h-[150px]"
                          />
                        ) : (
                          <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                            {results[summaryKey]}
                          </div>
                        )}
                        
                        <div className="mt-4 flex justify-between items-center">
                          <Badge variant={results[`${module}_full` as keyof typeof results] ? "default" : "secondary"}>
                            {results[`${module}_full` as keyof typeof results] ? "已生成完整版" : "待生成完整版"}
                          </Badge>
                          
                          <Button 
                            onClick={() => generateFullModule(module as 'application_form' | 'code' | 'document')}
                            disabled={loadingModule[module as keyof typeof loadingModule]}
                            size="sm"
                          >
                            {loadingModule[module as keyof typeof loadingModule] ? '生成中...' : '生成完整版'}
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
              

            </TabsContent>
            
            <TabsContent value="full" className="space-y-6">
              <div className="grid gap-6 md:grid-cols-1">
                {['application_form', 'code', 'document'].map((module) => {
                  const fullKey = `${module}_full` as keyof typeof results;
                  const Icon = getModuleIcon(module);
                  
                  return results[fullKey] && (
                    <Card key={module}>
                      <CardHeader>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <Icon className="h-5 w-5" />
                            <CardTitle>{getModuleTitle(module)}（完整版）</CardTitle>
                          </div>
                          <Button 
                            variant="outline"
                            onClick={() => copyToClipboard(results[fullKey]!)}
                          >
                            <Copy className="h-4 w-4 mr-2" />
                            复制
                          </Button>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="text-gray-600 whitespace-pre-wrap bg-gray-50 p-3 rounded max-h-96 overflow-y-auto">
                          {results[fullKey]}
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            </TabsContent>
          </Tabs>
        )}
      </div>
    </div>
  );
}